package com.edu.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.edu.springcloud.entities.CommonResult;
import com.edu.springcloud.entities.Payment;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @作者 five-five
 * @创建时间 2021/6/12
 */
@RestController
@Api("CircleBreakerController测试Ribbon轮询")
public class CircleBreakerController {
    //    public static final String SERVICE_URL = "http://nacos-payment-provider";
    @Value("${service-url.nacos-user-service}")
    private String SERVICE_URL;// = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @ApiOperation("测试fallback兜底方法")
    @RequestMapping(value = "/consumer/fallback/{id}", method = RequestMethod.GET)
//    @SentinelResource(value = "fallback")//没有配置
//    @SentinelResource(value = "fallback", blockHandler = "handlerBlockMethod")//只配置了blockHandler，只负责sentinel控制台配置异常
//    @SentinelResource(value = "fallback",fallback = "handlerFallback")//fallback只负责业务异常
//    @SentinelResource(value = "fallback", blockHandler = "handlerBlockMethod", fallback = "handlerFallback")
    @SentinelResource(
            value = "fallback",
            blockHandler = "handlerBlockMethod",
            fallback = "handlerFallback",
            exceptionsToIgnore = {NullPointerException.class, ArrayIndexOutOfBoundsException.class,IllegalArgumentException.class}
    )
    //fallback负责业务异常
    public CommonResult<Payment> fallback(@PathVariable Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
        } else if (result.getData() == null) {
            throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
        }
        return result;
    }

    public CommonResult handlerFallback(@PathVariable Long id, Throwable e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(444, "兜底异常handlerFallback,exception内容  " + e.getMessage(), payment);
    }

    public CommonResult handlerBlockMethod(@PathVariable Long id, BlockException e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(444, "handlerBlockMethod,exception内容  " + e.getClass().getCanonicalName(), payment);
    }

}
